package com.fcant.ssmcom.interceptor;

import com.fcant.ssmcom.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * LoginHandlerIntercepter
 * <p>
 * encoding:UTF-8
 *
 * @author Fcscanf
 * @description
 * @date 下午 17:01 2019-08-07/0007
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    /**
     * 配置不要拦截的URL
     */
    private final String[] URI = {"/page/login", "/user/login"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // TODO：对于不同权限的用户有不同的拦截-待完善

        StringBuffer requestURL = request.getRequestURL();
        //URL:除了login.jsp是可以公开访问的，其余的URL都要进行拦截控制
        if (requestURL.indexOf(URI[0]) > 0 || requestURL.indexOf(URI[1]) > 0) {
            return true;
        }
        //获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //判断session里是不是有登录信息
        if (user != null) {
            return true;
        }
        request.setAttribute("msg", "你还没有登录，请先登录！");
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
